<?php
//Start session
if (!isset($_SESSION))
{
    session_start();
}
?>
<?php

require_once("includes/db_connect.php");

$errmsg_arr = array();

$errflag = false;

// Clean inputs
$username = clean($_POST['username']);
$password = clean($_POST['password']);
$confirm = clean($_POST['confirm']);
$email = clean($_POST['email']);

// Validate inputs
if($username == '')
{
    $errmsg_arr[] = "Username missing";
    $errflag = true;
}

if($password == '')
{
    $errmsg_arr[] = "Password missing";
    $errflag = true;
}

if($confirm == '')
{
    $errmsg_arr[] = "Confirm password missing";
    $errflag = true;
}

if($email == '')
{
    $errmsg_arr[] = "Email missing";
    $errflag = true;
}
else
{
    if((preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email) == 0))
    {
        $errmsg_arr[] = "Invalid email address";
        $errflag = true;
    }
}

if(strcmp($password, $confirm) != 0)
{
    $errmsg_arr[] = "Passwords do not match";
    $errflag = true;
}

// Check for existing username
if($username != '')
{
    $sql = "SELECT * FROM dkp_users WHERE username='$username'";
    $result = mysql_query($sql);

    if($result)
    {
        if(mysql_num_rows($result) > 0)
        {
            $errmsg_arr[] = "Username already exists";
            $errflag = true;
        }

        @mysql_free_result($result);
    }
    else
    {
        die("Query failed" . mysql_error());
    }
}

// Check for existing email
if($email != '')
{
    $sql = "SELECT * FROM dkp_users WHERE email='$email'";
    $result = mysql_query($sql);

    if($result)
    {
        if(mysql_num_rows($result) > 0)
        {
            $errmsg_arr[] = "Email already exists";
            $errflag = true;
        }

        @mysql_free_result($result);
    }
    else
    {
        die("Query failed" . mysql_error());
    }
}

// Redirect back to registration in case of errors
if($errflag)
{
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: register.php");
    exit();
}

$passwordhash = md5($password);

$sql = "INSERT INTO dkp_users(username, password, email) VALUES('$username', '$passwordhash', '$email')";
$result = @mysql_query($sql);

if($result)
{
    $titleloc = "Create Account"; session_start();
    include("includes/header.php");

    echo "<h2>Registration Complete</h2>";
    echo "<br /><br />";
    echo '<a href="login.php">Please Login</a>';

    include("includes/footer.php");
}
else
{
    die("Query failed" . mysql_error());
}

?>
